import * as React from 'react';
import * as ReactDom from 'react-dom';
import '../styles.less';
import ParagraphCard from '../../../components/ParagraphCard'
import ReactEcharts from 'echarts-for-react'
import { insertImage } from '../../../utils/WordUtil';
import { openDialog } from '../../../utils/WordDialog';
import SidePanel from '../SidePanel';
import { PrimaryButton } from 'office-ui-fabric-react';

export interface StatProps {
  res: any,
  isNeedParent?: boolean
  search?: string
  viewIndex?: any
}

export interface StatStates {
  xAxis: any[]
  series: any[]
}

export default class Assistant extends React.Component<StatProps, StatStates> {
  echarts_react
  dialog
  constructor(props, context) {
    super(props, context);
    const { content, showUrl } = props.res
    const { xAxis, series } = content
    this.state = {
      xAxis,
      series
    }
  }

  click = async () => {
    return Word.run(async context => {
      const range = context.document.getSelection();
      range.load('text');
      range.font.color = 'red';
      await context.sync();
    });
  }

  getInsertData = () => {
    let echarts_instance = this.echarts_react.getEchartsInstance();
    let base64 = echarts_instance.getDataURL();
    return base64
  }

  insertChart = () => {
    let newImg = this.getInsertData()
    insertImage(newImg)
  }

  messageCallback = (arg) => {
    insertImage(arg.message)
    this.dialog.close();
  }

  dialogCallback = (asyncResult) => {
    if (asyncResult.status == "failed") {
    }
    else {
      console.info('弹窗打开成功')
      this.dialog = asyncResult.value;
      this.dialog.addEventHandler(Office.EventType.DialogMessageReceived, this.messageCallback);
    }
  }

  render() {
    const { res, search, isNeedParent = true, viewIndex } = this.props
    const { xAxis, series } = this.state
    const dataSeries = series.map(item => {
      return {
        ...item,
        type: 'bar'
      }
    })
    const option = {
      xAxis: {
        axisLabel: {
          interval: 0,
          rotate: isNeedParent ? -30 : ''
        },
        type: 'category',
        data: xAxis
      },
      yAxis: {
        type: 'value'
      },
      // grid: {
      //   y: 140
      // },
      series: dataSeries
    }

    // 修改图表数据
    const handleSerieshange = (newSeries) => {
      this.setState({
        series: newSeries
      })
      let chart = this.echarts_react.getEchartsInstance();
      chart.setOption(option)
    }

    const menuProps = [
      {
        key: 'view',
        text: '预览',
        iconProps: {
          iconName: 'View',
        },
        onClick: () => {
          openDialog(`/assistantDialog?keyword=${search}&index=${viewIndex}`, this.dialogCallback)
        }
      }, {
        key: 'download',
        text: '插入word',
        iconProps: {
          iconName: 'Download',
        },
        onClick: this.insertChart
      }
    ]

    return (
      <div className='stat'>
        {isNeedParent ?
          (<div onClick={() => openDialog(`/assistantDialog?keyword=${search}&index=${viewIndex}`, this.dialogCallback)}><ParagraphCard title={search} menuProps={{ items: menuProps }}>
            {res.content &&
              <ReactEcharts
                ref={(e) => { this.echarts_react = e; }}
                option={option}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
            }
          </ParagraphCard></div>) : (
            <React.Fragment>
              <ReactEcharts
                ref={(e) => { this.echarts_react = e; }}
                option={option}
                style={{ height: `${window.innerHeight - 100}px` }}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
              <div className="ms-clearfix">
                <SidePanel xAxis={xAxis} series={series} onChange={handleSerieshange} />
                <PrimaryButton className="pull-right" onClick={this.handleDialogInsert}>使用</PrimaryButton>
              </div>
            </React.Fragment>
          )
        }
      </div>
    );
  }

  handleDialogInsert = () => {
    let newImg = this.getInsertData()
    Office.context.ui.messageParent(newImg);
  }
}
